import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template



from xmw import tianya
import xmw
from xmw import error
import os
import urllib2, urllib
import uuid
import logging
import datetime
from google.appengine.ext import webapp
from google.appengine.ext import db
import random
from google.appengine.api import memcache

memCacheExpire = 1200

class MainPage(xmw.RequestHandler):


    def get_thread(self,status):
        thread=None

        keys=tianya.thread_level.keys()
        index = len(keys)-1
        while index >=0:
            #level=tianya.thread_level_keys[index]
            level=keys[index]
            index=index-1
            delta_seconds= tianya.thread_level[level]
            reason=random.randint(0,1)
            op="="
            if reason ==0:
                op="<"
            if reason ==1:
                op =">"
                
            #delta=datetime.timedelta(seconds=delta_seconds*reason/10)
            delta=datetime.timedelta(seconds=delta_seconds)
            now =   xmw.get_cn_now_time() 
            target=now - delta
            logging.info('query thread status:%s,level:%s,target time:%s'%(status,level,str(target)))
            q = db.GqlQuery("SELECT * FROM TianyaThread"+
                        " WHERE status =:1 "+
                        #"AND hot> :2 "+
                        "AND level = :2 "+
                        "AND last_refresh "+
                        op+
                        " :3 "+
                        "order by last_refresh ASC",
                        #status,-1,level,target)
                        status,level,target)
            q_count=q.count()
            
            t_index=0
            if q_count>=2:
                t_index=random.randint(0,q_count-1)
            logging.info('got %d thread,t_index:%d'%(q_count,t_index))
            lst_thread=q.fetch(t_index+1)
            if lst_thread is None:
                continue
            if len(lst_thread) ==0:
                continue
        
            thread = lst_thread[t_index]
            logging.info('got thread: thread_id:%s\ntitle:%s\nlevel:%s\nlastrefresh:%s'%(thread.thread_id,thread.title,thread.level,thread.last_refresh))
            
            break
        #logging.info('got thread:%s'%str(thread))
        return thread
    
    def get_thread2(self, status):
        """
        q = tianya.TianyaThread.all()
        q.filter('status = ', status)
        q.filter(' hot > ',0)
        thread = q.get()
        return thread
        """
        
        """
        q = tianya.TianyaThread.all()
        q.filter('status = ', status)
        q.filter(' hot > ',0)
        thread = q.get()
        """
        q = db.GqlQuery("SELECT * FROM TianyaThread"+
                        " WHERE status =:1 "+
                        "AND hot> :2 "+
                        "order by hot DESC",
                        status,-1)
        lst_thread=q.fetch(1)
        if lst_thread is None:
            return None
        if len(lst_thread) ==0:
            return None
        
        return lst_thread[0]
        
    def do_get(self):
        """
        Task1:update INIT thread to RUN
        Task2:on RUN thread,update the page_cnt,url_list,etc.
        """
                
        
        
        thread = self.get_thread2(xmw.Thread_Status.INIT)
        
        
        if thread is not None:
            thread.on_INIT() 
            #thread.put()
            template_values = { "thread":thread }
            self.render_template(template_values, 'thread.html')            
            return thread
    
        return None
    
        thread = self.get_thread(xmw.Thread_Status.RUN)
        
              
        if thread is not None:
            
            # if found in cache, ignor it!
            t=memcache.get(str(thread.thread_id))
            if t is None:
                x=random.randint(1,10)
                memcache.add(str(thread.thread_id),thread,memCacheExpire*x)
            else:
                logging.info("found thread:%s in cache,ignore"%str(thread.thread_id))
                return None
            thread.on_RUN()
            #thread.put()
            template_values = { "thread":thread }
            #print "--------"
            #print 'thread22 =%s' % thread.lst_page_url 
            self.render_template(template_values, 'thread.html')            
            return thread
        

        
        e = xmw.error.NO_THREAD_TO_TRACE("")
        self.render_error(e)
        return None
    
    def get(self):
        cnt=2
        while cnt >0:
            thread=self.do_get()
            if thread is not None:
                break
            else:
                cnt=cnt -1
        
        logging.info('final cnt=%d'%cnt)
        return cnt
    def get3(self):
        x=3
        while x>0:
            cnt=self.get_x()
            if cnt >10:
                x=x-1
                
                continue
            else:
                break
        logging.info('final x=%d'%x)
def main():
    application = webapp.WSGIApplication(
                                       [('/robot/thread_daemon', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
